<template>
	<div>音频可视化</div>
	<div class="modle_mus">
		<canvas id="myCanvas" ref="myCanvas" canvas-id="myCanvas"></canvas>
		<audio ref="audio" :src="audioSrc" controls></audio>
	</div>
</template>

<script setup>
	import { onMounted,ref } from 'vue'
	const audioSrc = ref(new URL('@/assets/11.mp3', import.meta.url).href)
	let isInit = false;
	let analyser = null,buffer = null,ctx = null,canvas = null;
	const myCanvas = ref(null)
	const audio = ref(null)
	onMounted(() => {
	  canvas = myCanvas.value;
	  const Ele = audio.value
	  if (canvas) {
	    ctx = canvas.getContext('2d');
	    // 这里可以添加初始化canvas的代码，例如设置背景色等
	    Ele.addEventListener('play',()=>{
	    	if(isInit) return
	    	const audioCtx = new AudioContext();//音频上下文
	    	const source = audioCtx.createMediaElementSource(Ele);//音频源节点
	    	analyser = audioCtx.createAnalyser();//音频分析节点
	    	source.connect(analyser);
	    	analyser.fftSize = 512;//默认2048
	    	buffer = new Uint8Array(analyser.frequencyBinCount); //类型化数组
	    	analyser.connect(audioCtx.destination);
	    	isInit = true;
	    })
	  }
	});
	const draw = ()=>{
		requestAnimationFrame(draw)
		if(!isInit) return
		const { width , height} = canvas;
		ctx.clearRect(0,0,width,height)
		analyser.getByteFrequencyData(buffer)
		const len = buffer.length / 2.5;
		const count = len * 2;//柱状图的数量
		const barWidth = width / count;//柱状图的宽度
		ctx.fillStyle = sjcolor2()
		for (let i = 0; i < len; i++) {
			const v = buffer[i]
			const barHeight = (v / 255) * height;
			const x1 = Math.round(i * barWidth + width / 2);
			const x2 = Math.round(width / 2 - (i + 1) * barWidth);
			const y = height - barHeight;
			ctx.fillRect(x1,y,barWidth - 2,barHeight)
			ctx.fillRect(x2,y,barWidth - 2,barHeight)
		}
	}
	const sjcolor = ()=> {
		let col = [
			'#f40ef7', '#83c44e', '#2196f3', '#e53935', '#00c0a5', '#eb8302', '#071751', '#720ef7'
		]
		let num = Math.round(Math.random() * 7 + 1)
		let color = col[num - 1]
		return color
	}
	const sjcolor2 = ()=> {
		let col = [
			'#f40ef7', '#83c44e', '#2196f3', '#e53935', '#00c0a5', '#eb8302', '#4769e5', '#720ef7','#00ff7f','#02EEFF'
		]
		let num = Math.round(Math.random() * 9 + 1)
		let color = col[num - 1]
		return col
	}
	draw()
</script>

<style>
	#myCanvas{
		height: 350px;
		margin: auto;
		display: block;
		background-color: #eee;
	}
	.modle_mus{
		text-align: center;
	}
</style>